#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <panel-applet.h>
#include <gtk/gtklabel.h>
#include <sys/inotify.h>
#include "getstatus.h"
#include "properties.h"
#include "watch.h"

gchar *filename;
int ino_fd, wd, delay=50, job_id;

static const char Context_menu_xml [] =
   "<popup name=\"button3\">\n"
   "   <menuitem name=\"Properties Item\" "
   "             verb=\"ESAppletProperties\" "
   "           _label=\"_Preferences...\"\n"
   "          pixtype=\"stock\" "
   "          pixname=\"gtk-properties\"/>\n"
   "   <menuitem name=\"About Item\" "
   "             verb=\"ESAppletAbout\" "
   "           _label=\"_About...\"\n"
   "          pixtype=\"stock\" "
   "          pixname=\"gtk-about\"/>\n"
   "</popup>\n";

static const gchar *const authors[] = { "Andrey Tikhonov <tiacorpo@gmail.com>", NULL };

static void display_about_dialog()
{
    gtk_show_about_dialog (NULL,
                           "program-name",   "Emerge Status Applet",
                           "authors",        authors,
                           "comments",       "Applet that shows current status of emerge",
                           "logo-icon-name", "utilities-terminal",
                           NULL);
}

static const BonoboUIVerb esapplet_menu_verbs [] = {
        BONOBO_UI_VERB ("ESAppletProperties", display_properties_dialog),
        BONOBO_UI_VERB ("ESAppletAbout", display_about_dialog),
        BONOBO_UI_VERB_END
};

static gboolean esapplet_fill (PanelApplet *applet,
                                       const gchar *iid,
                                       gpointer data)
{
    if (strcmp (iid, "OAFIID:EmergeStatusApplet") != 0)
        return FALSE;
    filename = calloc(1, 1000);
    filename = "/var/log/emerge.log";
    GtkWidget *label;
    label = gtk_label_new (NULL);
    gtk_container_add (GTK_CONTAINER (applet), label);
    gtk_widget_show_all (GTK_WIDGET (applet));
    update_status(label);
    /*<inotify stuff>*/
    ino_fd = inotify_init();
    wd = inotify_add_watch(ino_fd, filename, IN_MODIFY); // we are interested in log changes only
    /*</inotify stuff>*/
    job_id = g_timeout_add (delay, (GSourceFunc) &in_check, label);
    panel_applet_setup_menu (PANEL_APPLET (applet),
                             Context_menu_xml,
                             esapplet_menu_verbs,
                             NULL);
    return TRUE;
}

PANEL_APPLET_BONOBO_FACTORY ("OAFIID:EmergeStatusApplet_Factory",
                             PANEL_TYPE_APPLET,
                             "The Emerge Status Applet",
                             "0.1",
                             esapplet_fill,
                             NULL);
